package com.baizhi.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;
import java.util.Set;

@Aspect
@Configuration
public class CacheAspectHash {
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    RedisTemplate redisTemplate;
    @Around("@annotation(com.baizhi.annotation.AddCache)")
    public Object addCache(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        System.out.println("========进入环绕通知========");

        redisTemplate.setKeySerializer(new StringRedisSerializer());

        StringBuilder sb = new StringBuilder();

        String className = proceedingJoinPoint.getTarget().getClass().getName();
        /*sb.append(className);
        sb.append("-");*/
        String methodName = proceedingJoinPoint.getSignature().getName();
        sb.append(methodName);

        Object[] args = proceedingJoinPoint.getArgs();

        for (Object arg : args) {
            sb.append(args);
        }
        String key = sb.toString();

        //ValueOperations stringOpt = redisTemplate.opsForValue();
        //Boolean aBoolean = redisTemplate.hasKey(key);
        HashOperations hash = redisTemplate.opsForHash();
        Boolean aBoolean = hash.hasKey(className, key);

        Object result = null;
        if(aBoolean){

            result = hash.get(className,key);
        }else {

            result = proceedingJoinPoint.proceed();
            hash.put(className,key,result);
        }
        return result;
    }
    @AfterReturning("@annotation(com.baizhi.annotation.DelCache)")
    public void delCache(JoinPoint joinPoint){

        System.out.println("=====清除缓存======");

        String className = joinPoint.getTarget().getClass().getName();

        stringRedisTemplate.delete(className);

    }
}
